<template>
  <div>
    <a-modal
      :visible="visible"
      okText="提交"
      cancelText="关闭"
      :title="title"
      :maskClosable="false"
      :destroyOnClose="true"
      :keyboard="false"
      width="800px"
      @cancel="closeModal()"
      @ok="handleSubmit">

      <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">

        <a-form-item label="选择评价商品">
          <a-input
            v-decorator="['productName',{ rules: [{ required: true, message: '请选择商品!'}],trigger: 'blur' }]"
            @click="openAllGoodsModel"
            readOnly
            placeholder="选择评价商品"
          />
        </a-form-item>

        <a-form-item label="选择商品规格">
          <a-input
            v-model="skuName"
            @click="openGoodsSkuModel"
            readOnly
            :disabled="clickable"
            placeholder="选择评价商品的规格"
          />
        </a-form-item>

        <a-form-item label="用户昵称">
          <a-input
            v-decorator="['nickName']"
          />
        </a-form-item>
        <a-form-item label="评价星级">
          <a-rate
            v-decorator="['stars']"
          />
        </a-form-item>
        <a-form-item label="是否置顶">
          <a-radio-group
            :options="isOrOptions"
            v-decorator="['isTop']"
          />
        </a-form-item>
        <a-form-item label="评价图片">
          <upload-image
            :limit="10"
            v-decorator="['picUrl']"
          />
        </a-form-item>
        <a-form-item label="评价内容">
          <a-textarea
            v-decorator="['evaluation']"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      :visible="visible2"
      okText="选择"
      cancelText="取消"
      :title="title2"
      :maskClosable="false"
      :destroyOnClose="true"
      :keyboard="false"
      width="1000px"
      @cancel="closeModal2()"
      @ok="handleSubmit2">

      <search-table
        :url="url"
        ref="searchtable"
        :form="form2"
        @changeStatus=""
        :columns="columns"
        width="1000px"
      >
        <template slot="searchForm">
          <a-form layout="inline" :form="form2">

            <a-form-item label="商品名称">
              <a-input
                style="width:180px"
                v-decorator="[
                'goodsName',
              ]"
                placeholder="请输入商品名称"
              >
              </a-input>
            </a-form-item>

            <a-form-item label="商品分类">
              <a-tree-select
                allowClear
                style="width:180px"
                :replaceFields="{children:'children', title:'classifyName', key:'id', value: 'id' }"
                v-decorator="[
                'goodsClassificationId',
              ]"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="productClassifyList"
                placeholder="请选择"
                tree-default-expand-all
              >
              <span slot="title" slot-scope="{ key, value }">
                  {{ value }}
              </span>
              </a-tree-select>
            </a-form-item>

            <a-form-item label="商品分组">
              <a-tree-select
                allowClear
                style="width:180px"
                :replaceFields="{children:'children', title:'groupName', key:'id', value: 'id' }"
                v-decorator="[
                  'goodsGroupId',
                ]"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="productGroupList"
                placeholder="请选择"
                tree-default-expand-all
              >
                <span slot="title" slot-scope="{ key, value }">
                    {{ value }}
                </span>
              </a-tree-select>
            </a-form-item>

          </a-form>
        </template>
      </search-table>


    </a-modal>


    <a-modal
      :visible="visible3"
      okText="选择"
      cancelText="取消"
      :title="title3"
      :maskClosable="false"
      :destroyOnClose="true"
      :keyboard="false"
      width="1000px"
      @cancel="closeModal3()"
      @ok="handleSubmit3">

      <a-form :form="form3" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
        <MultiModel ref="mult" :skuIds="skuIds" :data="multiModelData"></MultiModel>
      </a-form>

    </a-modal>
  </div>
</template>
<script>
  import SearchTable from "@/components/form/SearchTable";
  import MultiModel from "./MultiModel";
  export default {
    name: 'appraise-edit',
    components: {
      SearchTable,
      MultiModel
    },
    props: {
      record: {
        type: Object,
        default() {
          return {}
        }
      },
      visible: {
        type: Boolean,
        default: false
      },
    },

    computed: {
      title() {
        return '新增虚拟评价'
      },
      userInfo(){
        return this.$store.getters.userInfo || {};
      }

    },
    data() {
      return {
        //多级型号
        multiModelData:[],
        url: '/goods/page',
        currentRecord: {},
        form2: this.$form.createForm(this, {name: 'table_search'}),
        form: this.$form.createForm(this, {name: 'coordinated'}),
        form3: this.$form.createForm(this, {name: 'skuform'}),
        isOrOptions: [
          {label: '是', value: 1},
          {label: '否', value: 0},
        ],
        visible2: false,
        title2: '请选择要评价的商品',
        visible3: false,
        title3: '请选择要评价的商品规格',
        //从后台获取的虚拟商品评价对象
        evaluation:{},
        AllGoods: [],
        // 选择的商品对象(这个数组只有一个元素) 为了方便操作 就没写成单独的对象
        chosenGood:[
          {goodsPicture:''}
        ],
        columns: [

          {
            title: '商品名称',
            dataIndex: 'goodsName',
            key: 'goodsName',
          },

          {
            title: '价格',
            dataIndex: 'salePrice',
            key: 'salePrice',
          },
          {
            title: '总可售库存',
            dataIndex: 'goodsInventoryTotal',
            key: 'goodsInventoryTotal',
          },

          {
            title: '销量',
            dataIndex: 'realSales',
            key: 'realSales',
          },

          {
            title: '状态',
            dataIndex: 'goodsStatus',
            key: 'goodsStatus',
            customRender:(text,record)=>{
              if (text===1){
                return '仓库中'
              } else if (text===2){
                return '上架'
              }else {
                return '已下架'
              }
            }
          },
          {
            title: '商品分类',
            dataIndex: 'goodsClassificationId',
            key: 'goodsClassificationId',
          },
          {
            title: '创建时间',
            dataIndex: 'createDate',
            key: 'createDate',
          }

        ],
        productClassifyList: [],//商品类型
        productGroupList: [],//商品分组


        skuIds:[],
        skuName:'',
        goodsId:'',
        clickable:true
      }
    },
    watch: {
      // 赋值操作
     async visible (value) {
        if (value && this.record.id) {
          await this.getInfo()
          // 获取型号
          // 这个时候还需要把ids 传过去
          this.$get('/goods/query',{id:this.goodsId}).then(res => {
            if(res && res.returnCode=='1000'){
              console.log('res商品信息',res)
              if(res.dataInfo.goodsModel==2){
                this.multiModelData=res.dataInfo.goodsSpecList || [];
                this.clickable = false
              }else{
                this.multiModelData=[]
                this.skuName='统一型号'
                this.clickable = true
              }
            }
          })
        }
      }
    },
    methods: {

   async getInfo () {
      const res = await  this.$get('/product/reviews/id', {id: this.record.id})
          if (res && res.returnCode === 1000) {
            this.skuName = res.dataInfo.skuName
            this.skuIds = res.dataInfo.skuIds
            this.skuIds = this.skuIds.split(',')
            this.goodsId = res.dataInfo.productId
            // this.goodsPicture = res.dataInfo.goodsPicture
            console.log(this.goodsId)
            // 把 商品信息id传给过去
            console.log('被修改的商品评价',res)
            this.evaluation= res.dataInfo || {}
            this.evaluation.source = ['', '小程序', '虚拟评价'][this.evaluation.source]
            this.$nextTick(()=> {
              const formItems = this.form.getFieldsValue();
              Object.keys(formItems).forEach(key => {
                formItems[key] = this.evaluation[key]
              })
              this.form.setFieldsValue(formItems);
            })
          }

      },

      handleSubmit() {
        console.log('----')
        this.form.validateFields((err, values) => {
          console.log(this.chosenGood[0].goodsPicture)
          // return
          if (!err) {
            this.skuIds = this.skuIds.join(',')

            if (this.chosenGood[0].goodsPicture==='' ){
              let url = '/product/reviews/update'
              // ★★★★★★★
              this.$post(url, {...values,
                id:this.evaluation.id,
                productId:this.goodsId,
                // goodsPicture:this.chosenGood[0].goodsPicture ||,
                skuIds:this.skuIds,
                skuName:this.skuName}).then(res => {
                if (res && res.returnCode === 1000) {
                  console.log('res', res)
                  this.$message.success('保存成功！')
                  this.skuName=''
                  this.closeModal(true)
                }
              })
            }else{
              let url = '/product/reviews/update'
              this.$post(url, {...values,
                id:this.evaluation.id,
                productId:this.goodsId,
                goodsPicture:this.chosenGood[0].goodsPicture,
                skuIds:this.skuIds,
                skuName:this.skuName}).then(res => {
                if (res && res.returnCode === 1000) {
                  console.log('res', res)
                  this.$message.success('保存成功！')
                  this.skuName=''
                  this.closeModal(true)
                }
              })
            }

          }
        });
      },

      closeModal(freshTable) {
        this.form.resetFields()
        this.$emit('cancel', freshTable)
      },

      async openGoodsSkuModel() {

      /*  if (!this.form.getFieldValue('productName')){
          this.$message.error('请先选择商品')
        }else {
          this.visible3 = true
        }*/
        this.visible3 = true
      },

      handleSubmit2() {
        this.$refs.searchtable.selectedRowKeys
        if ( this.$refs.searchtable.selectedRowKeys.length === 0) {
          return this.$message.warn('请先选择一项后再进行操作')
        }else if (this.$refs.searchtable.selectedRowKeys.length >1){
          return this.$message.warn('最多选择一个商品进行操作')
        }else{
          console.log(this.$refs.searchtable.selectedRowKeys)
          //this.chosenGood  被选择的 即将要做虚拟评价的商品
          this.chosenGood  = this.$refs.searchtable.dataSource.filter((item)=>{
            return item.id === this.$refs.searchtable.selectedRowKeys[0]
          })

          console.log('this.chosenGood',this.chosenGood)
          // 保存新的副本
          this.form.setFieldsValue({['productName']:this.chosenGood[0].goodsName})
          this.goodsId = this.chosenGood[0].id

          this.$get('/goods/query',{id:this.chosenGood[0].id}).then(res => {
            if(res && res.returnCode=='1000'){
              console.log('res商品信息',res)
              if(res.dataInfo.goodsModel==2){
                this.multiModelData=res.dataInfo.goodsSpecList || [];
                this.skuIds = []
                this.skuName = ''
                this.clickable = false
              }else{
                this.multiModelData=[]
                this.skuName='统一型号'
                this.clickable = true
              }
            }
          })
          this.visible2 = false
        }
      },
      async openAllGoodsModel() {
        await this.getProductClassify()
        await this.getProductGroup()
        this.visible2 = true
        // console.log('sss')
      },
      closeModal2(freshTable) {
        /*this.form.resetFields()
        this.$emit('cancel', freshTable)*/
        this.visible2 = false
      },

      //商品分类
      async getProductClassify() {
        let res = await this.$get('/goods/classify/tree', {
          shopId:this.userInfo.shopId || ''
        });
        if (res && res.returnCode == '1000') {
          this.productClassifyList = res.dataInfo || [];
        } else {
          this.productClassifyList = [];
        }
      },
      //商品分组
      async getProductGroup() {
        let res = await this.$get('/goods/group/tree', {
          shopId:this.userInfo.shopId || ''
        }, false, true);
        if (res && res.returnCode == '1000') {
          this.productGroupList = res.dataInfo || [];
        } else {
          this.productGroupList = [];
        }
      },


      closeModal3() {
        this.visible3 = false
      },
      handleSubmit3(){
        console.log('商品规格',this.$refs.mult.chosenData)
        this.skuIds = []
        this.skuName =''
        this.$refs.mult.chosenData.ids.forEach((item)=>{
          // push有问题
          this.skuIds.push(item.value)
          this.skuName= this.skuName+item.clabel+": "+item.label+" ;"
        })
        console.log('this.skuIds:',this.skuIds)
        this.visible3 = false
      },
    },

    async created() {
      // await this.acquireAllGoods()
    }


  }
</script>